import { createRouter, createWebHistory } from 'vue-router';
import routes from './modules';
import { isEmpty, isNotUndefined } from '../commons/utils';
import storage from '@/commons/storage';
import constants from '@/commons/constants';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

NProgress.configure({ showSpinner: false });

const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    if (to.path === from.path) return;
    NProgress.start();
    if (!routes[0].children.some(item => item.path === to.path)) {
        // 路由不存在跳转404
        next('/404');
        return;
    }
    if (isNotUndefined(to?.meta?.loginAuth) && !to?.meta?.loginAuth) {
        // 不校验是否登录
        next();
        return;
    }
    if (storage.has('Authorization')) {
        // 如果缓存有token，login页面跳转到首页，非login页面停留在当前页面
        if (to.path === '/login') {
            next('/');
        } else {
            next();
        }
        return;
    }
    // 如果没有有token，login页面停留在当前页，非login页跳转到登录页
    if (to.path === '/login') {
        next();
        return;
    }
    next('/login');
});
router.afterEach(() => {
    NProgress.done();
});
export { router };
